<?php

namespace app\api\controller;
use app\common\controller\Api;
use app\model\User;
use app\admin\model\Orders;
use app\api\service\PayConfig;
use app\api\service\PayService;
use GuzzleHttp\Psr7\Response;
use think\Db;
use think\Exception;

class Pay extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    /**
     * 小程序支付回调
     */
    public function xcxNotify()
    {
        $app=new PayConfig();
        $app->playConfig()->handlePaidNotify(function($message, $fail) {
            trace_log(json_encode($message),'pay_notify');
            $out_trade_no = $message['out_trade_no'];

            $orderModel = new Orders();
            $order = $orderModel->where('order_no', $message['out_trade_no'])->find();
            if (empty($order) || $order['status'] != $orderModel::STATUS_WAITPAY) {
                return true;
            }
            Db::startTrans();
            try {
                if ($message['return_code'] == 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                    // 用户是否支付成功
                    if ($message['result_code'] == 'SUCCESS') {

                        // 用户支付失败
                    } elseif ($message['result_code'] == 'FAIL') {
                        trace_log(json_encode($message),'pay_fail_notify');
                    }

                } else {
                    return $fail('通信失败，请稍后再通知我');
                }


                //
                if ($message['result_code'] == 'SUCCESS'){
                    $pay = new PayService($order['id'],$order['user_id']);
                    $pay->afterOrder();

                    if(!empty($order['parent_id'])){
                        $dailiUser = db('user')->where('id',$order['parent_id'])->find('group_id');
                        $group_id = $dailiUser['group_id'];
                        $yongjin = db('user_group')->where('id',$group_id)->value('yongjin');
                        $money = ($yongjin/100)*$order['total_price'];
                        $before = $dailiUser['total_income'];
                        db('user_money_log')->insert([
                            'user_id'=>$order['parent_id'],
                            'user_id2'=>$order['user_id'],
                            'type'=>2,//送小时 //2送金额
                            'money'=>$money,
                            'before'=>$before,
                            'after'=>round($before+$money,2),
                            'memo'=>"推广下单获取佣金{$money}",
                            'createtime'=>date("Y-m-d H:i:s",time()),
                        ]);
                        db('user')->where('id',$order['parent_id'])->update([
                            'total_income'=>round($dailiUser['total_income']+$money,2),
                            'total_income_history'=>round($dailiUser['total_income_history']+$money,2)
                        ]);
                    }

                }
                Db::commit();



                return true;
            } catch (\Exception $e) {
                Db::rollback();// 回滚事务
            }

        });

        $info = new Response(
           arrayToXML(['return_code' => 'SUCCESS', 'return_msg' => 'OK']),
            200,
            ['Content-Type' => 'application/xml']
        );
        echo $info;die();
//        return sprintf("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
    }

    /**
     * 公众号支付回调
     */
    public function gzhNotify()
    {
        $app=new PayConfig();
        $app->gzh_playConfig()->handlePaidNotify(function($message, $fail) {
            $out_trade_no = $message['out_trade_no'];
            $prefix = substr($out_trade_no, 0, 1);
            $orderModel = new Orders();
            $order = $orderModel->where('order_no', $message['out_trade_no'])->find();
            if (empty($order) || $order['status'] != $orderModel::STATUS_WAITPAY) {
                return true;
            }
            Db::startTrans();
            try {
                if ($message['return_code'] == 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                    // 用户是否支付成功
                    if ($message['result_code'] == 'SUCCESS') {

                        // 用户支付失败
                    } elseif ($message['return_code'] == 'FAIL') {
                        trace_log(json_encode($message),'pay_fail_notify');
                    }

                } else {
                    return $fail('通信失败，请稍后再通知我');
                }

                if ($message['result_code'] == 'SUCCESS'){
                    $pay = new PayService($order['id'],$order['user_id']);
                    $pay->afterOrder();
                }

                Db::commit();

                return true;
            } catch (\Exception $e) {
                Db::rollback();// 回滚事务
            }

        });

        $info = new Response(
            arrayToXML(['return_code' => 'SUCCESS', 'return_msg' => 'OK']),
            200,
            ['Content-Type' => 'application/xml']
        );
        echo $info;die();
//        return sprintf("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
    }

    /**
     * 退款回调
     */
    public function tuiBack()
    {
        $app=new PayConfig();
        $app->playConfig()->handlePaidNotify(function($message, $fail) {
            trace_log(json_encode($message), 'payback_notify');
        });
    }
}
